package soendtrs;

import helpers.d;
import soenudp.Command;
import soenudp.UDPException;
import soenudp.UDPHelper;
import soenudp.UDPMessage;

public class FakeFE {

    static int    LeaderPortMTL  = 20020;
    static int    LeaderPortTOR  = 20060;
    
    static String IP_OF_MTL_LEAD = "127.0.0.1"; // Leader will have to PING the FE 1st (the same a registering)
                                         // This can changes when the replica becomes a leader... 
                                         // Or by the election alogoritm.    
    static String IP_OF_TOR_LEAD = "127.0.0.1";
   
    static UDPHelper udpClient; // = new UDPHelper();

    /* 
     * Will timeout instead of wait & block. Must be used in the
     * front-end else the Front-End will deadlock after the
     * elections.
     */
    private static UDPMessage sendToDTRS(UDPMessage request) {
      UDPMessage response = null; 
      d.out("--\n" + request);
      try {
        udpClient.sendToNode(IP_OF_MTL_LEAD, LeaderPortMTL, request);
        response = udpClient.getMessageOrTimeout(5); // Timeout after 5 secs.
      } catch (UDPException e) {
        e.printStackTrace();
      } 
      return response;
    }
    /**
     * This is basically a dumm FronEnd with no CORBA
     */
    public static void main(String[] args)
    {
        try
        {
            udpClient = new UDPHelper();
            udpClient.startUnicastClient("FRONTEND");
            d.sleep(1*1000); // 1 Second delay
            
            /* ShowID, CustomerID, Tickets Amount, TransacID(optional for now), Optional Text */
           // UDPMessage aCheck = new UDPMessage("MTL101", "123456", Command.CHECK,   0,  0, null); 
          //  UDPMessage aResrv = new UDPMessage("MTL101", "123456", Command.RESERVE, 15, 0, null);
         //   UDPMessage aCancel= new UDPMessage("MTL101", "123456", Command.CANCEL,  10, 0, null);
            UDPMessage reply;
            
            // comment this loop if you just want a single request
            UDPMessage aExchag = new UDPMessage("MTL101", "311411", Command.EXCHANGE,  (long)2, 0, null, "TOR444",
                (long)4);
            
            while (true) // Maybe it will bother you all-ways receiving request
            {
                reply = sendToDTRS(aExchag);
                d.out("Dump:\n" + reply);
                d.sleep(5*1000); // 5 Seconds delay
                /*
                reply = sendToDTRS(aResrv);
                d.out("Dump:\n" + reply);      
                d.sleep(5*1000);
                
                reply = sendToDTRS(aCancel);
                d.out("Dump:\n" + reply);
                d.sleep(5*1000);
                */
            }
            
        } catch (UDPException e)
        {
            e.printStackTrace();
        }
    }

}
